﻿using System;
using System.Threading;
using System.Diagnostics;
using System.Web.Hosting;

namespace Noix.Web
{
    public class HttpListenerController
    {
        private Thread _pump;
        private bool _listening;
        private string _virtualDir;
        private string _physicalDir;
        private string[] _prefixes;
        private HttpListenerWrapper _listener;

        public HttpListenerController(string[] prefixes, string virtualDir, string physicalDir)
        {
            _prefixes = prefixes;
            _virtualDir = virtualDir;
            _physicalDir = physicalDir;
        }

        public void Start()
        {
            _listening = true;
            _pump = new Thread(new ThreadStart(Pump));
            _pump.Start();
        }

        public void Stop()
        {
            _listening = false;

            Process.GetCurrentProcess().Kill();
            _pump.Abort();
            _pump.Join();
        }

        private void Pump()
        {            
            _listener = (HttpListenerWrapper)ApplicationHost.CreateApplicationHost(
              typeof(HttpListenerWrapper), _virtualDir, _physicalDir);
            _listener.Configure(_prefixes, _virtualDir, _physicalDir);
            _listener.Start();

            while (_listening)
                _listener.ProcessRequest();
            
        }
    }
}